module top_module (
    input clk,
    input reset,
    input [3:1] s,
    output fr3,
    output fr2,
    output fr1,
    output dfr
); 

    parameter HIGH_LEVEL = 3'b111;
    parameter MID1_LEVEL = 3'b011;
    parameter MID2_LEVEL = 3'b001;
    parameter LOW_LEVEL = 3'b000;
    
    reg	[2:0]	level_state;
    reg	[3:0]	state;
    reg			flag;
    
    //保存前一状态
    always @(posedge clk) begin
        level_state <= s;
    end
    
    //水阀输出状态机
    always @(posedge clk) begin
        if(reset) begin
            state <= 4'b1111;
        end
        else begin
            case(s)
                HIGH_LEVEL:		state <= 4'b0000;
                MID1_LEVEL:		if(level_state == HIGH_LEVEL) begin
                					state <= 4'b0011;
                    				flag <= 1'b1;
                				end
                				else if(level_state == MID1_LEVEL && flag) begin
                                    state <= 4'b0011;
                                    flag <= 1'b1;
                                end
                				else begin
                    				state <= 4'b0010;
                                    flag <= 1'b0;
                				end
                MID2_LEVEL:		if(level_state == MID1_LEVEL) begin
                					state <= 4'b0111;
                    				flag <= 1'b1;
                				end
                				else if(level_state == MID2_LEVEL && flag) begin
                                    state <= 4'b0111;
                    				flag <= 1'b1;
                                end
                				else begin
                    				state <= 4'b0110;
                                    flag <= 1'b0;
                				end
                LOW_LEVEL:		state <= 4'b1111;
            endcase
        end
    end
    
    assign {fr3, fr2, fr1, dfr} = state;
    
endmodule
